package com.another.bidservice.utils.generator;

import com.another.bidservice.dao.mapper.CodeRuleDao;
import com.another.bidservice.entity.TCodeRule;
import com.another.common.utils.common.EmptyUtil;
import com.another.common.utils.common.MyException;
import com.another.common.utils.result.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : another
 * @version : 1.0
 * @description : 生成code工具类
 * @date : 2019/3/21  下午8:20
 */
@Component
public class GeneratorCodeForMysql {

    @Autowired
    private CodeRuleDao codeRuleDao;

    Logger logger=LoggerFactory.getLogger(this.getClass());

    /**
     * 通用code生成方法
     * @param codeRule
     * @return
     */
    public String GeneratorCode(TCodeRule codeRule){

        //判断是否传入生成规则
        if(EmptyUtil.isEmpty(codeRule)){
            throw new MyException(ResultEnum.ERROR.getCode(), "未传入代码生成规则！");
        }

        //判断是否传入规则名
        if(EmptyUtil.isEmpty(codeRule.getSeqTypeId())){
            throw new MyException(ResultEnum.ERROR.getCode(), "未传入代码生成规则名！");
        }

        //判断有没有传入生成序号数量
        if(EmptyUtil.isEmpty(codeRule.getSize())){
            codeRule.setSize(1);    //如果没传 默认为生成1个
        }

        //判断有没有传入规则ID
        if(EmptyUtil.isEmpty(codeRule.getPlatId())){
            codeRule.setPlatId("");     //给默认值1
        }

        //获取code
        codeRuleDao.getCode(codeRule);

        //判断是否生成成功
        if(EmptyUtil.isEmpty(codeRule.getCode())||EmptyUtil.isEmpty(codeRule.getIndex())){
            throw new MyException(ResultEnum.ERROR.getCode(), "代码生成失败了 😶！");
        }

        if(codeRule.getSize()>1){
            //处理code
            List<String> codeList=new ArrayList<>();
            int seq=Integer.parseInt(codeRule.getCode().substring(codeRule.getCode().length()-codeRule.getIndex(),codeRule.getCode().length()));
//            String prefix=codeRule.getCode().replace(seq+"","");
            String prefix=codeRule.getCode().substring(0,codeRule.getCode().length()-codeRule.getIndex());
            for(int i=0;i<codeRule.getSize();i++){

                StringBuffer codeTemp=new StringBuffer(prefix);

                String str=(seq+i)+"";
                for(int x=str.length();x<codeRule.getIndex();x++){
                    codeTemp.append("0");
                }
                codeList.add(codeTemp.toString()+(seq+i));
            }

            return String.join(",",codeList);


        }else{
            return codeRule.getCode();
        }


    }



}
